extends CharacterBody2D
class_name Character

signal choosing_finished
signal turn_end
signal character_selected

enum {LEFT,RIGHT}

const HURT_LABEL = preload("res://scenes/hurt_label.tscn")
const BUFFER_UI = preload("res://scenes/buffer_ui.tscn")
var side:int:
	set(_value):
		side = _value
		if _value == RIGHT:
			%AnimatedSprite2D.flip_h = true 

var attributes:Dictionary
var buffers:Array[Buffer]
var max_health:int:
	set(_value):
		max_health = _value
		attributes.max_health = max_health
		%HPBar.max_value = max_health
var health:int:
	set(_value):
		health = _value
		clamp(health,0,max_health)
		attributes.health = health
		%HPBar.max_value = max_health
		%HPBar.value = health
		%HPLabel.text = str(health) + "/" + str(max_health)
		if health == 0:
			die()
var max_mana:int:
	set(_value):
		max_mana = _value
		attributes.max_mana = max_mana
var mana:int:
	set(_value):
		mana = _value
		clamp(mana,0,max_mana)
		attributes.mana = mana

var speed:int:
	set(_value):
		speed = _value
		attributes.speed = speed
		
var skills:Array[Skill]
var cur_selected_skill:Skill

func _ready() -> void:
	TurnManager.new_round_begin.connect(on_new_round_begin)
	TurnManager.round_end.connect(on_round_end)
	max_health = attributes.max_health 
	health = max_health
	max_mana = attributes.max_mana
	mana = max_mana
	speed = attributes.speed
	%HPBar.max_value = max_health
	%HPBar.value = max_health
	%HPLabel.text = str(health) + "/" + str(max_health)
	%MPBar.max_value = max_mana
	%MPBar.value = mana
	%MPLabel.text = str(mana) + "/" + str(max_mana)
	%NameLabel.text = attributes.name

func append_skill(_skill_ui:Node):
	%SkillsContainer.add_child(_skill_ui)
	skills.append(_skill_ui.skill)
#轮到我执行操作
func start_choosing():
	for child in %SkillsContainer.get_children():
		child.can_selected = true
	pass

func select_skill(_skill_ui:Node):
	print("skill click",_skill_ui)
	for child in %SkillsContainer.get_children():
		if child != _skill_ui:
			child.on_selected = false
	cur_selected_skill = _skill_ui.skill

func cancel_select_skill():
	for child in %SkillsContainer.get_children():
		child.on_selected = false
	#cur_selected_skill = null
# 轮到我的回合
func take_turn(_target:Array,_skill:Skill):
	print("character take turn",_skill)
	%AnimatedSprite2D.play("attack1")
	_skill.use(_target)
	await get_tree().create_timer(0.4).timeout
	%AnimatedSprite2D.play("idle")
	emit_signal("turn_end")
	pass

func take_effect(_values:Dictionary):
	for key in _values.keys():
		if attributes.has(key):
			attributes[key] += _values[key]

func take_damage(_damage:Dictionary):
	var damage = 0
	if _damage.attack_power > attributes.physical_defense:
		damage += _damage.attack_power - attributes.physical_defense
	if _damage.magic_power > attributes.magic_defense:
		damage += _damage.magic_power - attributes.magic_defense
	health -= damage
	print("character,take damage:",damage)
	%AnimatedSprite2D.play("hurt")
	hurt(damage)
	if _damage.has("buffers"):
		var had_buffer:bool = false
		#如果已经有这个buffer，刷新buffer的回合时间，否则加上这个buffer
		print(self)
		for buff in _damage.buffers:
			var has_this_buff = false
			for mybuff in buffers:
				print("bufferid:",mybuff.id,buff.id,self)
				if mybuff.id == buff.id:
					has_this_buff = true
					mybuff.max_round = buff.max_round
					mybuff.cur_round = buff.max_round
			if has_this_buff == false:
				apply_buffer(buff)
	await get_tree().create_timer(0.4).timeout
	%AnimatedSprite2D.play("idle")

func hurt(_value):
	var label = HURT_LABEL.instantiate()
	add_child(label)
	label.set_value(_value)
		
func die():
	pass

func apply_buffer(_buffer:Buffer):
	print("apply buffer:",_buffer.id)
	buffers.append(_buffer)
	$MarginContainer3/BuffersContainer.add_child(_buffer.buffer_ui)
	if DataManager.data.buffers[_buffer.id].triggle == Buffer.ONE_TIME_ONLY:
		_buffer.apply(self)
	
func remove_buffer(_buffer:Buffer):
	print("remove buffer:",_buffer.id)
	buffers.erase(_buffer)
	$MarginContainer3/BuffersContainer.remove_child(_buffer.buffer_ui)
	_buffer.remove(self)

# 新回合
func on_new_round_begin():
	# 执行掉血等各种buff
	for buffer in buffers:
		if DataManager.data.buffers[buffer.id].triggle == Buffer.ON_ROUND_START:
			buffer.apply(self)

func on_round_end(_round):
	print("on_round end:",self)
	# 处理掉没有次数的buff
	for buffer in buffers:
		buffer.cur_round -= 1
		if buffer.cur_round == 0:
			remove_buffer(buffer)

func end_of_choice():
	print("end_of_choice")
	for child in %SkillsContainer.get_children():
		child.on_selected = false
		child.can_selected = false
	emit_signal("choosing_finished")
	pass



func _on_area_2d_mouse_entered() -> void:
	%AnimatedSprite2D.material.set_shader_parameter("width",1)


func _on_area_2d_mouse_exited() -> void:
	%AnimatedSprite2D.material.set_shader_parameter("width",0)


func _on_area_2d_input_event(_viewport: Node, event: InputEvent, _shape_idx: int) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.is_pressed():
		print(TurnManager.cur_operating_player)
		if TurnManager.cur_operating_player != null:
			TurnManager.cur_selected_character = self
			end_of_choice()
